package com.usst.handle;


import org.springframework.stereotype.Controller;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.mysql.jdbc.StringUtils;
import com.usst.entity.Comment;
import com.usst.entity.Post;
import com.usst.entity.PostAnswer;
import com.usst.service.CommentService;
import com.usst.service.PostAnswerService;
import com.usst.service.PostService;


@Controller
public class CommentHandler2 extends DefaultHandler {

	private PostService postService;
	
	private PostAnswerService postAnswerService;
	
	private CommentService commentService;
	
	private Comment comment;
	
	public CommentHandler2() {
		super();
	}
	
	public CommentHandler2(PostService postService, PostAnswerService postAnswerService,
			CommentService commentService) {
		this();
		this.postService = postService;
		this.postAnswerService = postAnswerService;
		this.commentService = commentService;
	}
    
    @Override
    public void startDocument() throws SAXException {
    	
    }
    
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
    
    }
    
	@Override
    public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
        if ("row".equals(name)) {
        	
            comment= new Comment();
            comment.setCommentId(Long.valueOf(attributes.getValue("Id")));
            comment.setPostId(Long.valueOf(attributes.getValue("PostId")));
            
            if (!StringUtils.isNullOrEmpty(attributes.getValue("Score"))) {
            	comment.setScore(Long.valueOf(attributes.getValue("Score")));
            }
            
            if (!StringUtils.isNullOrEmpty(attributes.getValue("Text"))) {
            	comment.setText(attributes.getValue("Text"));
            }
            
            if (!StringUtils.isNullOrEmpty(attributes.getValue("CreationDate"))) {
            	comment.setCreationDate(attributes.getValue("CreationDate"));
            }
            
            if (!StringUtils.isNullOrEmpty(attributes.getValue("UserId"))) {
            	comment.setUserId(Long.valueOf(attributes.getValue("UserId")));
            }
        	  
        }
    }
    
    @Override
    public void endElement(String uri, String localName, String name) throws SAXException {
        if (comment != null && "row".equals(name) && comment.getCommentId() >= 20000000 && comment.getCommentId() < 25000000) {
        	Post postRequest = postService.findOne(comment.getPostId());
        	if (postRequest != null) {
        		commentService.save(comment);
        	} else {
        		PostAnswer postAnswer = postAnswerService.findOne(comment.getPostId());
        		if (postAnswer != null) {
        			commentService.save(comment);
        		}
        		postAnswer = null;
        	}
        	postRequest = null;
        	comment = null;
        }
    }
    
}
